<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>3D Model Viewer</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
            width: 100vw;
            height: 100vh;
        }
        #canvas {
            width: 100%;
            height: 100%;
            display: block;
        }
        .controls {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            gap: 10px;
            z-index: 100;
        }
        .settings-panel {
            position: fixed;
            top: 20px;
            right: 20px;
            background: rgba(0, 0, 0, 0.7);
            padding: 15px;
            border-radius: 8px;
            color: white;
            font-family: Arial, sans-serif;
            z-index: 100;
        }
        .settings-panel label {
            display: block;
            margin-bottom: 10px;
        }
        .settings-panel input {
            margin-left: 10px;
            vertical-align: middle;
        }
        button {
            padding: 10px 20px;
            background: #2196F3;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.3s;
        }
        button:hover {
            background: #1976D2;
        }
        .loading {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 20px;
            border-radius: 8px;
            font-family: Arial, sans-serif;
        }
    </style>
    <script async src="static/lib/es-module-shims.js"></script>
    <script type="importmap">
        {
            "imports": {
                "three": "./static/lib/three.module.js",
                "three/addons/": "./static/lib/examples/jsm/"
            }
        }
    </script>
</head>
<body>
<canvas id="canvas"></canvas>
<div id="loading" class="loading">加载中...</div>
<div class="controls">
    <button onclick="window.viewer.toggleAutoRotate()">切换自动旋转</button>
    <button onclick="window.viewer.resetCamera()">重置视角</button>
</div>
<div class="settings-panel">
    <label>
        背景颜色:
        <input type="color" value="#f0f0f0" oninput="window.viewer.updateBackgroundColor(this.value)">
    </label>
    <label>
        主光源亮度:
        <input type="range" min="0" max="2" step="0.1" value="1.5" oninput="window.viewer.updateMainLightIntensity(this.value)">
    </label>
    <label>
        环境光亮度:
        <input type="range" min="0" max="2" step="0.1" value="0.6" oninput="window.viewer.updateAmbientLightIntensity(this.value)">
    </label>
    <label>
        填充光亮度:
        <input type="range" min="0" max="2" step="0.1" value="0.8" oninput="window.viewer.updateFillLightIntensity(this.value)">
    </label>
    <label>
        背光亮度:
        <input type="range" min="0" max="2" step="0.1" value="0.6" oninput="window.viewer.updateBackLightIntensity(this.value)">
    </label>
</div>

<script type="module">
    import * as THREE from 'three';
    import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
    import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
    import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';

    class ModelViewer {
        constructor() {
            this.scene = null;
            this.camera = null;
            this.renderer = null;
            this.model = null;
            this.controls = null;
            this.autoRotate = true;
            this.loadingElem = document.getElementById('loading');
            this.lights = {};

            this.init();
        }

        setupLighting() {
            // 环境光 - 提供基础照明
            this.lights.ambient = new THREE.AmbientLight(0xffffff, 0.6);
            this.scene.add(this.lights.ambient);

            // 主要方向光 - 从右上方照射
            this.lights.main = new THREE.DirectionalLight(0xffffff, 1.5);
            this.lights.main.position.set(5, 5, 5);
            this.lights.main.castShadow = true;
            this.lights.main.shadow.mapSize.width = 2048;
            this.lights.main.shadow.mapSize.height = 2048;
            this.lights.main.shadow.camera.near = 0.1;
            this.lights.main.shadow.camera.far = 40;
            const d = 15;
            this.lights.main.shadow.camera.left = -d;
            this.lights.main.shadow.camera.right = d;
            this.lights.main.shadow.camera.top = d;
            this.lights.main.shadow.camera.bottom = -d;
            this.lights.main.shadow.bias = -0.001;
            this.scene.add(this.lights.main);

            // 补光 - 从左前方照射
            this.lights.fill = new THREE.DirectionalLight(0xffffff, 0.8);
            this.lights.fill.position.set(-5, 3, 2);
            this.scene.add(this.lights.fill);

            // 背光 - 从后方照射，创造轮廓
            this.lights.back = new THREE.DirectionalLight(0xffffff, 0.6);
            this.lights.back.position.set(0, 3, -5);
            this.scene.add(this.lights.back);

            // 添加半球光 - 提供更自然的环境光照
            this.lights.hemi = new THREE.HemisphereLight(0xffffff, 0x444444, 0.4);
            this.lights.hemi.position.set(0, 20, 0);
            this.scene.add(this.lights.hemi);
        }

        init() {
            // 创建场景
            this.scene = new THREE.Scene();
            this.scene.background = new THREE.Color(0xf0f0f0);

            // 创建相机
            this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
            this.camera.position.set(0, 1, 3);

            // 创建渲染器
            this.renderer = new THREE.WebGLRenderer({
                canvas: document.getElementById('canvas'),
                antialias: true
            });
            this.renderer.setSize(window.innerWidth, window.innerHeight);
            this.renderer.setPixelRatio(window.devicePixelRatio);
            this.renderer.shadowMap.enabled = true;
            this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
            this.renderer.outputColorSpace = THREE.SRGBColorSpace;
            this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
            this.renderer.toneMappingExposure = 1.0;

            // 设置灯光
            this.setupLighting();

            // 创建轨道控制器
            this.controls = new OrbitControls(this.camera, this.renderer.domElement);
            this.controls.enableDamping = true;
            this.controls.dampingFactor = 0.05;
            this.controls.maxPolarAngle = Math.PI / 1.5;
            this.controls.minDistance = 2;
            this.controls.maxDistance = 10;

            // 加载GLB模型
            const loader = new GLTFLoader();
            const dracoLoader = new DRACOLoader();
            dracoLoader.setDecoderPath('/static/lib/examples/jsm/libs/draco/');
            loader.setDRACOLoader(dracoLoader);

            loader.load(
                '1.glb',
                (gltf) => this.onModelLoaded(gltf),
                (xhr) => this.onProgress(xhr),
                (error) => this.onError(error)
            );

            window.addEventListener('resize', () => this.onWindowResize(), false);
            this.animate();
        }

        onModelLoaded(gltf) {
            this.model = gltf.scene;

            this.model.traverse((child) => {
                if (child.isMesh) {
                    child.castShadow = true;
                    child.receiveShadow = true;
                    if (child.material) {
                        child.material.envMapIntensity = 1.0;
                        child.material.needsUpdate = true;
                    }
                }
            });

            const box = new THREE.Box3().setFromObject(this.model);
            const center = box.getCenter(new THREE.Vector3());
            const size = box.getSize(new THREE.Vector3());
            const maxDim = Math.max(size.x, size.y, size.z);
            const scale = 2 / maxDim;
            this.model.scale.multiplyScalar(scale);
            this.model.position.sub(center.multiplyScalar(scale));

            // 添加地面
            const groundGeometry = new THREE.PlaneGeometry(100, 100);
            const groundMaterial = new THREE.ShadowMaterial({ opacity: 0.3 });
            const ground = new THREE.Mesh(groundGeometry, groundMaterial);
            ground.rotation.x = -Math.PI / 2;
            ground.position.y = -1;
            ground.receiveShadow = true;
            this.scene.add(ground);

            this.scene.add(this.model);
            this.loadingElem.style.display = 'none';
        }

        // 新增的控制方法
        updateBackgroundColor(color) {
            this.scene.background = new THREE.Color(color);
        }

        updateMainLightIntensity(intensity) {
            if (this.lights.main) {
                this.lights.main.intensity = parseFloat(intensity);
            }
        }

        updateAmbientLightIntensity(intensity) {
            if (this.lights.ambient) {
                this.lights.ambient.intensity = parseFloat(intensity);
            }
        }

        updateFillLightIntensity(intensity) {
            if (this.lights.fill) {
                this.lights.fill.intensity = parseFloat(intensity);
            }
        }

        updateBackLightIntensity(intensity) {
            if (this.lights.back) {
                this.lights.back.intensity = parseFloat(intensity);
            }
        }

        onProgress(xhr) {
            if (xhr.lengthComputable) {
                const percent = (xhr.loaded / xhr.total * 100).toFixed(1);
                this.loadingElem.textContent = `加载中: ${percent}%`;
            }
        }

        onError(error) {
            console.error('加载模型时发生错误:', error);
            this.loadingElem.textContent = '加载失败，请检查模型文件';
        }

        onWindowResize() {
            this.camera.aspect = window.innerWidth / window.innerHeight;
            this.camera.updateProjectionMatrix();
            this.renderer.setSize(window.innerWidth, window.innerHeight);
        }

        animate() {
            requestAnimationFrame(() => this.animate());

            if (this.controls) {
                this.controls.update();
            }

            if (this.model && this.autoRotate) {
                this.model.rotation.y += 0.01;
            }

            this.renderer.render(this.scene, this.camera);
        }

        toggleAutoRotate() {
            this.autoRotate = !this.autoRotate;
        }

        resetCamera() {
            this.camera.position.set(0, 1, 3);
            this.camera.lookAt(0, 0, 0);
            if (this.controls) {
                this.controls.reset();
            }
        }
    }

    // 创建查看器实例并保存到全局作用域
    window.viewer = new ModelViewer();
</script>
</body>
</html>